<template>
  <div class="detail-page">
    <el-button @click="goBack" class="back-btn" type="primary">返回首页</el-button>
    <div v-if="!isArticleDetail">
      <h2>{{ moduleTitle }}</h2>
      <div class="article-list">
        <div 
          class="article-item" 
          v-for="item in list" 
          :key="item.id" 
          @click="showArticleDetail(item)"
        >
          <h3>{{ item.title }}</h3>
          <p>{{ item.brief }}</p>
          <span class="publish-time">{{ formatTime(item.publishTime) }}</span>
        </div>
      </div>
    </div>
    <div v-else class="article-detail">
      <el-button @click="isArticleDetail = false" type="success">返回列表</el-button>
      <h2>{{ currentArticle.title }}</h2>
      <span class="detail-publish-time">{{ formatTime(currentArticle.publishTime) }}</span>
      <div v-html="currentArticle.content" class="content"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useInforTechStore } from "@/stores/information/technology";
import { useInforNewsStore } from "@/stores/information/news";
import { useInforArticleStore } from "@/stores/information/article";

const techStore = useInforTechStore();
const newsStore = useInforNewsStore();
const articleStore = useInforArticleStore();
const route = useRoute();
const router = useRouter();
const module = route.params.module as string;

const list = ref([]);
const isArticleDetail = ref(false);
const currentArticle = ref({ title: '', content: '', publishTime: '' });
const moduleTitle = ref('');

// 格式化时间显示
const formatTime = (timeString: string) => {
  if (!timeString) return '';
  const date = new Date(timeString);
  return date.toLocaleString(); // 格式化成本地时间字符串
};

// 按发布时间排序（最新在前）
const sortByPublishTime = (items: any[]) => {
  return [...items].sort((a, b) => {
    const timeA = a.publishTime ? new Date(a.publishTime).getTime() : 0;
    const timeB = b.publishTime ? new Date(b.publishTime).getTime() : 0;
    return timeB - timeA; // 降序排列，最新的在前
  });
};

const fetchData = async () => {
  try {
    let rawData;
    // 根据模块获取原始数据
    if (module === 'tech') {
      rawData = await techStore.getAllTech();
      moduleTitle.value = '特色医疗技术';
    } else if (module === 'news') {
      rawData = await newsStore.getAllNews();
      moduleTitle.value = '最新医疗新闻';
    } else if (module === 'article') {
      rawData = await articleStore.getAllArticles();
      moduleTitle.value = '健康科普文章';
    }

    // 打印原始数据结构，确认数据格式
    console.log('原始数据:', rawData);

    // 根据模块类型进行字段映射
    let mappedItems = [];
    if (module === 'tech') {
      mappedItems = (rawData || []).map(item => ({
        id: item.techId,
        title: item.techTitle,
        brief: item.techContent.substring(0, 100) + '...',
        content: item.techContent,
        img: item.techImg,
        publishTime: item.publishTime // 保留发布时间用于排序
      }));
    } else if (module === 'news') {
      mappedItems = (rawData || []).map(item => ({
        id: item.newsId,
        title: item.newsTitle,
        brief: item.newsContent.substring(0, 100) + '...',
        content: item.newsContent,
        img: item.newsImg,
        publishTime: item.publishTime
      }));
    } else if (module === 'article') {
      mappedItems = (rawData || []).map(item => ({
        id: item.articleId,
        title: item.articleTitle,
        brief: item.articleContent.substring(0, 100) + '...',
        content: item.articleContent,
        img: item.articleImg,
        publishTime: item.publishTime
      }));
    }

    // 按发布时间排序
    list.value = sortByPublishTime(mappedItems);
  } catch (error) {
    console.error('数据获取失败:', error);
    list.value = [];
  }
};

const showArticleDetail = (article) => {
  currentArticle.value = article;
  isArticleDetail.value = true;
};

const goBack = () => {
  router.push({ name: 'HomeIndex' });
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.detail-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
    background-image: url("@/assets/OIP-C.webp");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 100vh;
}

.back-btn {
  margin-bottom: 20px;
}

h2 {
  color: #333;
  border-bottom: 2px solid #f5f5f5;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

/* 列表样式 - 一行显示一条 */
.article-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}

.article-item {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.article-item:hover {
  background: #f9f9f9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.article-item h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 1.1rem;
}

.article-item p {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 0.95rem;
  line-height: 1.6;
}

.publish-time {
  font-size: 0.85rem;
  color: #999;
}

/* 详情页样式 */
.article-detail {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}

.detail-publish-time {
  display: inline-block;
  margin: 10px 0 20px 0;
  color: #999;
  font-size: 0.9rem;
}

.content {
  color: #333;
  line-height: 1.8;
  font-size: 1rem;
}

.content p {
  margin-bottom: 16px;
}
</style>
